package com.zzy.algorithm.linkedList;

import com.zzy.algorithm.model.ListNode;

/**
 * LeetCode - 206 ：反转链表
 *
 * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
 *
 * 解题思路：
 * 方法一：递归
 *  递归到尾结点，然后反转相邻两个节点指针
 * 方法二：迭代
 *  引入前驱、后继、当前节点三个中间变量，依次反转指针
 *
 *
 */
public class Q12_ReverseLinkedList {

    public static void main(String[] args) {
        Q12_ReverseLinkedList q12_reverseLinkedList = new Q12_ReverseLinkedList();
        ListNode solution = q12_reverseLinkedList.solution2(ListNode.list5);
        while(solution != null){
            System.out.println(solution.val);
            solution = solution.next;
        }
    }

    /**
     * 递归
     * @param head
     * @return
     */
    private ListNode solution(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = solution(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    /**
     * 迭代
     * @param head
     * @return
     */
    private ListNode solution2(ListNode head){
        ListNode prev = null;
        ListNode next;
        ListNode curr = head;
        while(curr != null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

}
